package com.example.demo.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionTemplate;

import com.example.demo.dao.SequenceMapper;
import com.example.demo.exception.SPIPException;

import io.shardingsphere.api.HintManager;
import tk.mybatis.mapper.genid.GenId;

public class SequenceUtil implements GenId<Long>{
	private static final Logger LOGGER = LoggerFactory.getLogger(SequenceUtil.class);
	
	static SequenceMapper sequenceMapper;
	static TransactionTemplate transactionTemplate;
	static {
		sequenceMapper=SpringBeanUtil.getBean(SequenceMapper.class);
		transactionTemplate=SpringBeanUtil.getBean(TransactionTemplate.class);
	}

	public static Long getId(String name) {
		return transactionTemplate.execute(status->{
		        Long result = null;
		        try {
		        	HintManager.getInstance().setMasterRouteOnly();
		        	result = sequenceMapper.getIncrementValue(name);
		        	if(result==null) {
		        		throw new SPIPException(name+":自定义序列不存在");
		        	}
		    		sequenceMapper.updateCurrentValue(name);
		        } catch (Exception e) {
		        	LOGGER.error("生成id异常:",e);
		            status.setRollbackOnly();
		        }
		        return result;
		    });
	}
	

	@Override
	public Long genId(String table, String column) {
		return getId(table);
	}
}
